﻿using LinqToExcel;
using SchoolCommunicationSystem.Models;
using SCS.Business;
using SCS.Common.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SchoolCommunicationSystem.Controllers
{
    public class LearnerController : Controller
    {
        MembershipService _membershipServices = new MembershipService();
        LearnerServices _learnerServices = new LearnerServices();
        Parent2Services _parent2Services = new Parent2Services();
        //
        // GET: /Learner/

        /// <summary>
        /// Index
        /// </summary>
        /// <returns>RedirectToAction("WebGrid")</returns>
        public ActionResult Index()
        {
            return RedirectToAction("WebGrid");
        }

        /// <summary>
        /// AddLearner
        /// </summary>
        /// <returns>View</returns>
        public ActionResult AddLearner()
        {
            return View();
        }

        /// <summary>
        /// EditLearner
        /// </summary>
        /// <returns>View</returns>
        public ActionResult EditLearner()
        {
            return View();
        }

        /// <summary>
        /// Bind Web Grid and also do paging
        /// </summary>
        /// <param name="page">1</param>
        /// <param name="searchString">string</param>
        /// <param name="sort">name</param>
        /// <param name="sortDir">ASC</param>
        /// <returns>view</returns>
        public ActionResult WebGrid(int page = 1, int ClassID = 0, string searchString = "", string sort = "name", string sortDir = "ASC")
        {
            const int pageSize = 25;
            var totalRows = _learnerServices.CountLearner(searchString);
            if (totalRows <= pageSize)
            {
                page = 1;
            }
            sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
            /*
                        var validColumns = new[] { "learnerID", "firstname", "lastname", "address", "gender" };
                        if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
                            sort = "learnerID";
                        */
            IEnumerable<Learner> learner = null;
            if (string.IsNullOrEmpty(searchString) && ClassID==0)
            {
                learner = _learnerServices.GetLearnerPaging(page, pageSize);
            }
            else
            {
                learner = _learnerServices.SearchTeacherPaging(page, pageSize, searchString,ClassID);
            }
            var className = _learnerServices.GetClassSelectList().Select(t => new SelectListItem()
            {
                Text = t.className,
                Value = t.classID.ToString(),
            }).ToList();
            var data = new LearnerListViewModels()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Learners = learner,
                ClassSelectList = className
            };
            return View(data);
        }

        /// <summary>
        /// Pre Create learner
        /// </summary>
        /// <returns>View</returns>
        public ActionResult Create()
        {
            var className = _learnerServices.GetAllClassInSchoolYears().Select(t => new SelectListItem()
            {
                Text = t.className,
                Value = t.classID.ToString()
            }).ToList();
            var gender = new List<SelectListItem>();
            gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
            gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
            ViewBag.Genders = gender;
            var model = new LearnerAndClassModels { Learners = null, ClassSelectList = className };
            ViewBag.IsUpdate = false;
            return View("_Learner", model);
        }

        /// <summary>
        /// get all learners
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>view</returns>
        public ActionResult View(int id)
        {
            var data = _learnerServices.GetLearner(id);
            if (Request.IsAjaxRequest())
            {
                Learner _learner = _learnerServices.GetLearner(id);
                var className = _learnerServices.GetAllClassInSchoolYears().Select(t => new SelectListItem()
                {
                    Text = t.className,
                    Value = t.classID.ToString()
                }).ToList();

                var model = new LearnerAndClassModels { Learners = _learner, ClassSelectList = className };
                return View("_ViewLearner", model);
            }
            else

                return View(data);
        }

        /// <summary>
        /// edit learner info
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult Edit(int id)
        {
            if (Request.IsAjaxRequest())
            {
                var gender = new List<SelectListItem>();
                gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
                gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
                ViewBag.Genders = gender;
                Learner _learner = _learnerServices.GetLearner(id);
                var className = _learnerServices.GetClassSelectList().Select(t => new SelectListItem()
                {
                    Text = t.className,
                    Value = t.classID.ToString(),
                }).ToList();

                var model = new LearnerAndClassModels { Learners = _learner, ClassSelectList = className };

                ViewBag.IsUpdate = true;
                return View("_Learner", model);
            }
            else

                return View();
        }

        /// <summary>
        /// Pre SCS Register Exist Parent Account
        /// </summary>
        /// <param name="id">learnerID</param>
        /// <returns>View</returns>
        public ActionResult AddParentIDToLearner(int id, string searchString = "")
        {
            var model = new ListParentsAddExistViewModel
            {
                ParentsList = _membershipServices.SearchParentsUser(searchString),
                learnerID = id
            };

            return View(model);
        }

        /// <summary>
        /// SCS Register Exist Parent Account
        /// </summary>
        /// <param name="id">parentID</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult AddParentExistAccount(ListParentsAddExistViewModel model)
        {
            int learnerID = model.learnerID;
            int parentID = model.parentID;
            bool status = _learnerServices.AddParentIDToLearner(learnerID, parentID);
            if (status != true)
            {
                ModelState.AddModelError(string.Empty, "Chưa chọn phụ huynh!");
                var models = new ListParentsAddExistViewModel
                {
                    ParentsList = _membershipServices.SearchParentsUser(""),
                    learnerID = learnerID
                };

                return View("AddParentIDToLearner", models);
            }
            else
            {
                return RedirectToAction("WebGrid");
            }
        }

        /// <summary>
        /// Pre SCS Register
        /// </summary>
        /// <param name="id">parentID</param>
        /// <returns>View</returns>
        public ActionResult EditParent(int id)
        {
            if (ModelState.IsValid)
            {
                var gender = new List<SelectListItem>();
                gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
                gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
                ViewBag.Genders = gender;

                Learner _learner = _learnerServices.GetLearner(id);

                var model = new DK
                {
                    Learners = _learner,
                    UserName = string.Empty,
                    Email = string.Empty,
                    Password = string.Empty
                };
                var returnUrl = Request["ReturnUrl"];
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    model.ReturnUrl = returnUrl;
                }
                return View(model);
            }
            else

                return View();
        }

        /// <summary>
        /// SCS Register
        /// </summary>
        /// <param name="DK">DK</para`m>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult EditParent(DK DK)
        {
            Learner _learner = DK.Learners;
            if (ModelState.IsValid)
            {
                var userToSave = new MembershipUser
                {
                    userName = DK.UserName,
                    email = DK.Email,
                    password = DK.Password
                };
                userToSave.userID = _membershipServices.GetMemberID();

                var createStatus = _membershipServices.CreateUser(userToSave, 2);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, "[Tên đăng nhập] hoặc [Email] đã tồn tại");

                    var genderParent = new List<SelectListItem>();
                    genderParent.Add(new SelectListItem() { Text = "Nam", Value = "M" });
                    genderParent.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
                    ViewBag.Genders = genderParent;
                    var model = new DK
                    {
                        Learners = _learner,
                        UserName = string.Empty,
                        Email = string.Empty,
                        Password = string.Empty
                    };

                    return View(DK);
                }
                else
                {

                    Parent parentToAdd = new Parent();
                    parentToAdd.parentName = DK.parent.parentName;
                    parentToAdd.gender = DK.parent.gender;
                    parentToAdd.mobile = DK.parent.mobile;
                    parentToAdd.tel = DK.parent.tel;
                    parentToAdd.email = DK.Email;
                    parentToAdd.userID = userToSave.userID;
                    _parent2Services.AddParent(parentToAdd);

                    _learner.learnerID = DK.Learners.learnerID;
                    _learner.lastName = DK.Learners.lastName;
                    _learner.gender = DK.Learners.gender;
                    _learner.firstName = DK.Learners.firstName;
                    _learner.dateOfBirth = DK.Learners.dateOfBirth;
                    _learner.classID = DK.Learners.classID;
                    _learner.birthPlace = DK.Learners.birthPlace;
                    _learner.address = DK.Learners.address;
                    _learner.parentID = parentToAdd.parentID;
                    _learnerServices.UpdateLearnerDK(_learner);

                }
                return RedirectToAction("ParentsAccount", "AccountManagement");
            }
            var gender = new List<SelectListItem>();
            gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
            gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
            ViewBag.Genders = gender;
            return View(DK);
        }

        /// <summary>
        /// Delete a learner
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult Delete(int id)
        {
            _learnerServices.DeleteLearner(id);
            return RedirectToAction("WebGrid");
        }

        /// <summary>
        /// Create and edit a learner info
        /// </summary>
        /// <param name="learner">LearnerAndClassModels</param>
        /// <param name="Command">string</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult CreateEditLearner(LearnerAndClassModels learner, string Command)
        {
            // Validate the model being submitted
            if (!ModelState.IsValid)
            {

                return PartialView("_Learner", learner);

            }

            else if (Command == "Save")
            {
                Learner _learner = new Learner();
                _learner = learner.Learners;
                bool check = _learnerServices.CreateLearner(_learner);
                if (check)
                {
                    TempData["Msg"] = "Học sinh đã được tạo thành công";
                    ModelState.Clear();
                    return RedirectToAction("WebGrid", "Learner");
                }
            }

            else if (Command == "Update")
            {
                Learner _learner = learner.Learners;
                bool check = _learnerServices.UpdateLearner(_learner);
                if (check)
                {
                    TempData["Msg"] = "Thông tin học sinh đã được sửa thành công";
                    ModelState.Clear();
                    return RedirectToAction("WebGrid", "Learner");
                }

            }

            return PartialView("_Learner", learner);
        }

        /// <summary>
        /// Pre import list of learner
        /// </summary>
        /// <returns>View</returns>
        public ActionResult ImportLearner()
        {
            return View();
        }

        /// <summary>
        /// Import list of learner
        /// </summary>
        /// <param name="fc">FormCollection</param>
        /// <param name="uploadFile">HttpPostedFileBase</param>
        /// <returns>RedirectToAction("WebGrid")</returns>
        [HttpPost]
        public ActionResult ImportLearner(FormCollection fc, HttpPostedFileBase uploadFile)
        {
            try
            {
                if (uploadFile.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"),
                    Path.GetFileName(uploadFile.FileName));
                    uploadFile.SaveAs(filePath);

                    var excel = new ExcelQueryFactory();
                    excel.FileName = filePath;
                    excel.AddMapping<Learner>(x => x.firstName, "Họ đệm");
                    excel.AddMapping<Learner>(x => x.lastName, "Tên");
                    excel.AddMapping<Learner>(x => x.dateOfBirth, "Ngày sinh");
                    excel.AddMapping<Learner>(x => x.gender, "Giới tính");
                    excel.AddMapping<Learner>(x => x.birthPlace, "Nơi sinh");
                    excel.AddMapping<Learner>(x => x.address, "Địa chỉ");
                    var details = from x in excel.Worksheet<Learner>("Sheet1")
                                  select x;
                    foreach (var detail in details)
                    {
                        Learner learner = new Learner();
                        learner.firstName = detail.firstName;
                        learner.lastName = detail.lastName;
                        learner.dateOfBirth = detail.dateOfBirth;
                        learner.gender = detail.gender;
                        learner.birthPlace = detail.birthPlace; learner.address = detail.address;
                        learner.deactive = false;
                        _learnerServices.CreateLearner(learner);
                    }
                }
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
            return RedirectToAction("WebGrid");
        }
    }
}
